// src/store/CounterStore.js

// 1. 定义初始状态 (Initial State)
import React, {createContext, useReducer} from "react";

export const initialState = {
  count: 0,
};

// Define the action interface
interface CounterAction {
  type: 'INCREMENT' | 'DECREMENT' | 'RESET' | 'ADD_BY';
  payload?: number;
}



// Define the state type
type CounterState = typeof initialState;


export interface CounterContextType {
  state: CounterState;
  dispatch: React.Dispatch<CounterAction>;
}


// 2. 定义 Reducer 函数
// 这个函数接收当前的 state 和一个 action 对象，然后返回一个新的 state。
export const reducer = (state: CounterState = initialState, action: CounterAction) => {
  switch (action.type) {
    case 'INCREMENT':
      return {...state, count: state.count + 1};
    case 'DECREMENT':
      return {...state, count: state.count - 1};
    case 'RESET':
      return {...state, count: 0};
    case 'ADD_BY':
      const incrementValue = action.payload || 0;
      return {...state, count: state.count + incrementValue};
    default:
      // 如果 action 类型不匹配，直接返回原 state
      return state;
  }
};

export const CounterContext = createContext<CounterContextType | undefined>(undefined);

export const CounterProvider = ({children}: { children: React.ReactNode }) => {
  // 使用 useReducer Hook
  // 它返回当前的状态 (state) 和一个用于分发 action 的函数 (dispatch)
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <CounterContext.Provider value={{state, dispatch}}>
      {
        children
      }
    </CounterContext.Provider>
  )
}
